const cheerio = require('cheerio');
const iconv  = require('iconv-lite');
const install = require('superagent-charset');
const request = require('superagent');

let pad = function (number, length, pos) {
	var str = "%" + number;
	while (str.length < length) {
		//向右边补0
		if ("r" == pos) {
			str = str + "0";
		} else {
			str = "0" + str;
		}
	}
	return str;
}

let toHex = function (chr, padLen) {
	if (null == padLen) {
		padLen = 2;
	}
	return pad(chr.toString(16), padLen);
}

function chinese2Gb2312(data) {
	var gb2312 = iconv.encode(data.toString('UCS2'), 'GB2312');
	var gb2312Hex = "";
	for (var i = 0; i < gb2312.length; ++i) {
		gb2312Hex += toHex(gb2312[i]);
	}
	return gb2312Hex.toUpperCase();
}

let dytt = function(keyword) {

	let url = 'http://s.dydytt.net/plus/search.php?keyword=' + chinese2Gb2312(keyword);

	let promise = new Promise((resolve, reject) => {
		superagent = install(request);
		superagent.get(url).charset('gb2312').end(function(err,res) {

			if (err) reject(err);

			let $ = cheerio.load(res.text, {decodeEntities: false});
			let $ul = $('.bd3r .co_content8').children('ul');
			let len = $ul.find('table').length;
			var arr = [];

			if (len>0) {
				$ul.find('table').each(function() {

					let $title = $(this).find('tr').eq(0).find('td').eq(1).find('a');
					let title = $title.html().split('《')[1];

					if (title.indexOf('<font color="red">'+keyword+'</font>》')==0) {
						let obj = {};
						obj.title = $title.html();
						obj.href = $title.attr('href');
						obj.desc = $(this).find('tr').eq(1).find('td').html();
						obj.from = 'ddyt';
						arr.push(obj);
					}
				});
			}

			resolve(arr);
		});
	});
	return promise;
}

module.exports = dytt;
